/**
 * @file index.tsx
 * @description 登陆页面
 */
import React, {useState} from 'react';
import {StyleSheet, Image} from 'react-native';
import HeaderScreen from '../../components/header';
import {
  Box,
  Text,
  Input,
  Icon,
  Button,
  Center,
  useToast,
  Pressable,
} from 'native-base';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { isEmpty,isStringEmpty,getPermissionsList,buttonPermissions, } from "../../utils/untils";
import { setUserInfo } from "../../redux/reducers/userReducer";
import {useDispatch, useSelector } from 'react-redux';
import rootReducer from '../../redux/reducers';
import * as request from "../../request/common";
import { useFocusEffect } from '@react-navigation/native';
import storage from "../../utils/storage";
import GlobalEmitter from "../../utils/global";
import * as Device from "../../utils/device";

const LoginScreen: React.FC<ComponentProp> = ({navigation}) => {

  // 变量
  const [show, setShow] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [userName, setUserName] = useState('');
  const [password, setPassword] = useState('');
  const toast = useToast();

  // redex
  const userInfo = useSelector((state: ReturnType<typeof rootReducer>) => state.userInfo.user);
  const dispatch = useDispatch();
  /**
   * 导航获取焦点、失去焦点
   */
  useFocusEffect(
    React.useCallback(() => {
      dispatch(setUserInfo({}));
      storage.save({ key: "userInfo", data: {}});
      GlobalEmitter.emit("logoutClearDispatchingList", {
      });
      console.log('Screen was focused');
      return () => {
        console.log('Screen was unfocused');
      };
    }, [])
  )

  

  /**
   * @description 点击登陆处理函数
   */
  const handleLogin = () => {
    setIsLoading(true);
    let msg = '';
    if (isStringEmpty(userName)) {
      msg = '请输入账号';
    } else if (isStringEmpty(password)) {
      msg = '请输入密码';
    }
    if (msg.length > 0) {
      toast.show({
        placement: "top",
        description: msg,
      });
      setIsLoading(false);
      return;
    }
    request.login(userName.trim(), password.trim()).then((response: any) => {

      if (response.code == 40020) {
        let authList = getPermissionsList(JSON.parse(response.data.role_info.role_details || []),JSON.parse(response.data.extra_auth || "[]"));
        response.data.pageAuth = authList[0];
        response.data.btnAuth = authList[1];
        let deliver =  buttonPermissions('ddlb','32',response.data.btnAuth); // 订单发货
        let stock = buttonPermissions('scdgl','9',response.data.btnAuth); // 生产单出库
        if(deliver == false || stock == false) {
          toast.show({
            placement: "top",
            description: '您还没有权限，请联系管理员',
          });
          setIsLoading(false);
          return ;
        }
        dispatch(setUserInfo(response.data));
        storage.save({ key: "userInfo", data: response.data});
        toast.show({
          placement: "top",
          description: '登录成功',
        });
        setIsLoading(false);
        navigation && navigation.goBack();
      } else {
        toast.show({
          placement: "top",
          description: response?.message || '登录失败',
        });
      }
      setIsLoading(false);
    });
  };

  const handleParentMethod = (message: string) => {
    console.log(message);
  };

  return (
    <Box bg="gray.100" borderRadius="md" w="100%" h="100%">
      <HeaderScreen navigation={navigation} title="登录"></HeaderScreen>
      <Box alignItems="center" mt="16">
        <Image
          style={{width: 88, height: 88}}
          source={require('../../assets/images/logo.png')}></Image>
      </Box>
      <Center w="96%">
        <Input
          mt="60"
          w="90%"
          size="md"
          onChangeText={text => setUserName(text)}
          variant="underlined"
          InputLeftElement={
            <Icon
              as={<MaterialIcons name="person" />}
              size={5}
              ml="2"
              mr="4"
              color="dark.100"
            />
          }
          placeholder="请输入账号"
        />
        <Input
          mt="4"
          w="90%"
          type={ show?"text":"password"}
          onChangeText={text => setPassword(text)}
          variant="underlined"
          InputLeftElement={
            <Icon
              as={<MaterialIcons name="https" />}
              size={5}
              ml="2"
              mr="4"
              color="dark.100"
            />
          }
          InputRightElement={
            <Pressable onPress={() => setShow(!show)}>
              <Icon
                as={
                  <MaterialIcons
                    name={show ? 'visibility' : 'visibility-off'}
                  />
                }
                size={5}
                mr="2"
                color="muted.400"
              />
            </Pressable>
          }
          placeholder="请输入密码"
        />
        <Button isLoading={isLoading} onPress={handleLogin} isLoadingText="登录中..." w="90%" mt="6"  bg="#4F94F9" _pressed={{ bg:"#4F94F9" }}>
          登录
        </Button>
      </Center>
      <Box alignItems="center" mt="50">
        <Text color="dark.400">版本号V{Device.appVersion}</Text>
      </Box>
    </Box>
  );
};

export default LoginScreen;
